'use client';

import { useState } from 'react';
import { useApp } from '@/contexts/AppContext';
import { useToast } from '@/components/Toast';
import { products, categories } from '@/lib/mockData';

interface CategoryPageProps {
  params: {
    id: string;
  };
}

export default function CategoryPage({ params }: CategoryPageProps) {
  const { dispatch } = useApp();
  const { showToast, ToastContainer } = useToast();
  const [addingToCart, setAddingToCart] = useState<string | null>(null);
  const [buyingNow, setBuyingNow] = useState<string | null>(null);

  const categoryId = params.id;
  const category = categories.find(c => c.id === categoryId);
  const categoryProducts = products.filter(p => p.category === categoryId);

  const handleAddToCart = async (product: any) => {
    const productId = product.id;
    setAddingToCart(productId);
    dispatch({ type: 'ADD_TO_CART', payload: product });
    
    setTimeout(() => {
      setAddingToCart(null);
      showToast(`已将 ${product.name} 加入购物车！`, 'success');
    }, 500);
  };

  const handleBuyNow = async (product: any) => {
    const productId = product.id;
    setBuyingNow(productId);
    
    // 模拟加载
    setTimeout(() => {
      setBuyingNow(null);
      // 直接跳转到订单页面
      window.location.href = `/order?product=${product.id}`;
    }, 500);
  };

  if (!category) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-800 mb-4">分类不存在</h1>
          <a href="/" className="text-blue-600 hover:text-blue-700">返回首页</a>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        {/* 面包屑导航 */}
        <nav className="text-sm text-gray-600 mb-8">
          <a href="/" className="hover:text-gray-800">首页</a>
          <span className="mx-2">/</span>
          <span className="text-gray-800">{category.name}</span>
        </nav>

        {/* 分类标题和描述 */}
        <div className="text-center mb-12">
          <div className="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-r from-yellow-400 to-orange-400 rounded-full mb-6">
            <span className="text-4xl">{category.icon}</span>
          </div>
          <h1 className="text-4xl font-bold text-gray-800 mb-4">{category.name}</h1>
          <p className="text-xl text-gray-600 max-w-2xl mx-auto">{category.description}</p>
          <div className="mt-4 text-sm text-gray-500">
            共 {categoryProducts.length} 款盲盒产品
          </div>
        </div>

        {/* 产品网格 */}
        <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
          {categoryProducts.map((product) => (
            <div key={product.id} className="bg-white rounded-lg shadow-lg hover:shadow-xl transition-shadow overflow-hidden">
              <div className={`h-48 bg-gradient-to-br ${product.bgColor} flex items-center justify-center`}>
                <div className="w-24 h-24 bg-white/20 rounded-lg flex items-center justify-center shadow-xl backdrop-blur-sm">
                  <span className="text-3xl">{category.icon}</span>
                </div>
              </div>
              <div className="p-4">
                <div className="flex items-center justify-between mb-2">
                  <span className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black px-2 py-1 rounded text-xs font-bold">
                    {product.probability}
                  </span>
                  <div className="text-2xl font-bold text-gray-800">
                    ￥{product.price}
                  </div>
                </div>
                <h3 className="font-semibold text-lg text-gray-900 mb-2">
                  {product.name}
                </h3>
                <p className="text-sm text-gray-600 mb-3">
                  {product.description}
                </p>
                <div className="text-sm text-gray-500 mb-4">
                  <div className="flex justify-between">
                    <span>原价值:</span>
                    <span className="font-semibold">{product.originalValue}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>库存:</span>
                    <span className="font-semibold">{product.stock} 件</span>
                  </div>
                </div>
                <div className="space-y-3">
                  <a href={`/product/${product.id}`} className="w-full block bg-gray-50 text-gray-700 py-3 px-4 rounded-lg text-center hover:bg-gray-100 transition-colors font-medium border border-gray-200">
                    🔍 查看详情
                  </a>
                  <div className="grid grid-cols-2 gap-2">
                    <button
                      onClick={() => handleAddToCart(product)}
                      disabled={addingToCart === product.id}
                      className="border-2 border-orange-500 text-orange-600 font-medium py-2.5 px-3 rounded-lg hover:bg-orange-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                    >
                      {addingToCart === product.id ? '添加中...' : '🛒 购物车'}
                    </button>
                    <button
                      onClick={() => handleBuyNow(product)}
                      disabled={buyingNow === product.id}
                      className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-2.5 px-3 rounded-lg hover:shadow-lg transition-shadow disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                    >
                      {buyingNow === product.id ? '处理中...' : '⚡ 立即购买'}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* 如果没有产品 */}
        {categoryProducts.length === 0 && (
          <div className="text-center py-16">
            <div className="text-6xl mb-4">📦</div>
            <h3 className="text-xl font-semibold text-gray-800 mb-2">暂无产品</h3>
            <p className="text-gray-600">该分类下还没有盲盒产品，敬请期待！</p>
          </div>
        )}
      </div>
      <ToastContainer />
    </div>
  );
}